package com.yanq.liancar.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.VehicleBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.ToastUtil;
import com.yanq.liancar.util.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyCarInfoActivity extends BaseToolbarActivity {

    @BindView(R.id.myCarInfo_chepai)
    TextView myCarInfoChepai;
    @BindView(R.id.myCarInfo_chejia)
    TextView myCarInfoChejia;
    @BindView(R.id.myCarInfo_fadongji)
    TextView myCarInfoFadongji;
    @BindView(R.id.myCarInfo_time)
    TextView myCarInfoTime;
    @BindView(R.id.myCarInfo_pinpai)
    TextView myCarInfoPinpai;
    @BindView(R.id.myCarInfo_chexi)
    TextView myCarInfoChexi;
    @BindView(R.id.myCarInfo_chexing)
    TextView myCarInfoChexing;
    @BindView(R.id.tv_defaultCar)
    TextView tv_tv_defaultCar;
    @BindView(R.id.ll_obd)
    LinearLayout LlOBD;
    @BindView(R.id.tv_obd)
    TextView tv_obd;
    @BindView(R.id.et_OBD)
    EditText et_OBD;
    @BindView(R.id.img_saomiao)
    ImageView img_saomiao;
    @BindView(R.id.tv_save)
    TextView tv_save;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right2)
    ImageView ivRight2;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.common_toolbar)
    Toolbar commonToolbar;
    @BindView(R.id.action_bar)
    AppBarLayout actionBar;
    @BindView(R.id.rl_obd)
    RelativeLayout rl_obd;
    private String carId = "";
    private int defaultCar,type; //type:1   已绑定obd   type：0为绑定obd

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //让布局向上移来显示软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        setContentView(R.layout.activity_my_car_info);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);

        mTvTitle.setText("车辆信息");
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("解绑车辆");
        mTvRight.setTextColor(getResources().getColor(R.color.main_color));
        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(carId)) {
                    showUnbindDialog("您确定要解除绑定这辆车吗",1);
                }
            }
        });

        Bundle bundle = getIntent().getExtras();
        if (!bundle.isEmpty()) {
            carId = bundle.getString("carId");
            if (!TextUtils.isEmpty(carId)) {
                initOkGo();
            }
        }

    }

    /*获取CARDetails*/
    private void initOkGo() {
        OkGo.<String>get(Config.s + "llc/userCar/queryCarDetail")
                .tag(this)
                .params("id", carId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        VehicleBean bean = gson.fromJson(response.body(), VehicleBean.class);
                        if (bean.isIsSuccess()) {
                            myCarInfoChepai.setText("" + bean.getData().getDriNum());
                            myCarInfoChejia.setText("" + bean.getData().getCarDriNum());
                            myCarInfoFadongji.setText("" + bean.getData().getMotorNum());
                            myCarInfoTime.setText("" + bean.getData().getRegisterDate());
                            myCarInfoPinpai.setText("" + bean.getData().getCarBrand());
                            myCarInfoChexi.setText("" + bean.getData().getCarCate());
                            myCarInfoChexing.setText("" + bean.getData().getCarType());
                            defaultCar=bean.getData().getDefaultCar();
                            if (bean.getData().getDefaultCar() == 1) {
                                tv_tv_defaultCar.setSelected(true);
                            } else {
                                tv_tv_defaultCar.setSelected(false);
                            }
                            if (TextUtils.isEmpty(bean.getData().getObdNum())) {
                                type=0;
                                LlOBD.setVisibility(View.VISIBLE);
                                tv_obd.setVisibility(View.GONE);
                                tv_save.setText("保存");
                            } else {
                                type=1;
                                LlOBD.setVisibility(View.GONE);
                                tv_obd.setVisibility(View.VISIBLE);
                                tv_obd.setText(bean.getData().getObdNum());
                                tv_save.setText("解绑OBD");
                            }
                        }
                    }
                });
    }


    private void showUnbindDialog(String title, final int status) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_unbind, null);
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(view);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.9);
        view.setLayoutParams(params);
        dialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
        dialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        dialog.setCanceledOnTouchOutside(false);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView submit = (TextView) view.findViewById(R.id.submit);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        TextView tvTitle = (TextView) view.findViewById(R.id.title);
        tvTitle.setText(title);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (status==1){
                    initUnBind();
                }else {
                    initUnBindOBD();
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                return;
            }
        });
        dialog.show();
    }

    //解绑车辆
    private void initUnBind() {
        OkGo.<String>get(Config.s + "llc/userCar/removeUserCar")
                .tag(this)
                .params("id", carId)
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            RxToast.success("解绑成功");
                            carId = "";
                            finish();
                        } else {
                            RxToast.info("解绑失败");
                        }
                    }
                });
    }

    //解绑OBD
    private void initUnBindOBD() {
        OkGo.<String>get(Config.s + "llc/odbbind/removeODB")
                .tag(this)
                .params("obdNum", tv_obd.getText().toString().trim())
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            RxToast.success("解绑成功");
                            carId = "";
                            finish();
                        } else {
                            RxToast.info("解绑失败");
                        }
                    }
                });
    }

    @OnClick({R.id.img_saomiao, R.id.tv_save,R.id.rl_obd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_saomiao:
                Intent intent=new Intent(this, ScanerCodeActivity.class);
                intent.putExtra("where","BindCarActivity");
                startActivityForResult(intent,001);
                break;
            case R.id.tv_save:
                if (type==0){
                    if (!TextUtils.isEmpty(et_OBD.getText().toString().trim())){
                        ToastUtil.showProgressDialog(this);
                        initOkGo1();
                    }
                }else {
                    showUnbindDialog("您确定要解除绑定OBD设备吗",2);
                }
                break;
            case R.id.rl_obd:
//                if (type==1){
//                    showUnbindDialog("您确定要解除绑定OBD设备吗",2);
//                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==001){
                et_OBD.setText(data.getStringExtra("code"));
            }
        }
    }

    //添加车辆接口
    private void initOkGo1() {
        OkGo.<String>post(Config.s + "llc/userCar/addUserCar")
                .tag(this)
                .params("token", UserBean.getcToken(mContext))
                .params("driNum",myCarInfoChepai.getText().toString().trim())
                .params("carDriNum", myCarInfoChejia.getText().toString().trim())
                .params("motorNum", myCarInfoFadongji.getText().toString().trim())
                .params("registerDate", myCarInfoTime.getText().toString().trim())
                .params("carBrand",myCarInfoPinpai.getText().toString().trim())
                .params("carType", myCarInfoChexi.getText().toString().trim())
                .params("carCate", myCarInfoChexing.getText().toString())
                .params("defaultCar", defaultCar+"")
                .params("obdNum", et_OBD.getText().toString().trim())
                .params("id", carId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            ToastUtil.dismissProgressDialog();
                            finish();
                            Toast.makeText(MyCarInfoActivity.this,  "保存成功", Toast.LENGTH_SHORT).show();
                        } else {
                            ToastUtil.dismissProgressDialog();
                            Toast.makeText(MyCarInfoActivity.this, "" + bean.getOutputMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
}
